<template>
  <basic-container class="production-page">
    <div style="width: 100%; display: flex">
      <div style="width: 25%; min-width: 300px; margin-right: 30px">
        <div class="bindLeft">
          <h2>单据信息</h2>
          <avue-form ref="barCodeForm" v-model="sheetNoInfo" :option="barCodeOption" @reset-change="emptytChange" @submit="submit">
            <template slot="purchaseOrderNo">
              <el-input
                placeholder="扫码识别带出或选择采购单"
                name="purchaseOrderNo"
                v-model="sheetNoInfo.purchaseOrderNo"
                class="input-with-select"
                @keyup.enter.native="getPurcahasePartDetail(sheetNoInfo.purchaseOrderNo)"
              >
                <el-button slot="append" icon="el-icon-search" @click="openSheetNoModal"></el-button>
              </el-input>
            </template>
          </avue-form>
        </div>
      </div>
      <!-- </el-col>
      <el-col :span="19"> -->
      <div style="width: 75%; min-width: 500px">
        <h2>采购单物料信息</h2>
        <avue-crud
          class="partInfoCrud"
          :option="option"
          :data="data"
          v-model="form"
          ref="crud"
          @selection-change="selectionChange"
          @row-save="partInfoRowSave"
          @row-update="partInfoRowUpdate"
        >
          <template slot-scope="{ row, index }" slot="receivingQuantityForm"
            ><el-input
              v-model="row.receivingQuantity"
              placeholder="请输入 本次收货数量"
              oninput="value= value.replace(/^\D*(\d*(?:\.\d{0,5})?).*$/g, '$1')"
              @input="receivingQuantityChange(row, index)"
            ></el-input
          ></template>
        </avue-crud>
      </div>
    </div>
    <!-- </el-col>
    </el-row> -->
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
  </basic-container>
</template>
<script>
import { getList, getSheetDetail, receivingSubmit, checkReceiving } from '@/api/product/purchaseOrderReceipt';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import { mapGetters } from 'vuex';
import { selectInput, focusInput, ransferToNumber } from '@/util/helpers';
export default {
  name: '',
  components: { CommonModalTemplate },
  inject: ['globalStartLoad', 'globalEndLoad'],
  data() {
    return {
      sheetNoInfo: {},
      barCodeOption: {
        submitBtn: true,
        emptyBtn: true,
        submitText: '收料',
        labelWidth: 100,
        column: [
          {
            label: '采购单',
            type: 'search',
            prop: 'purchaseOrderNo',
            span: 24,
            placeholder: '扫码识别带出或选择采购单',
            formslot: true,
            rules: [
              {
                required: true,
                message: '请扫码识别带出或选择采购单',
                trigger: 'submit'
              }
            ]
          },
          {
            label: '供应商',
            prop: 'vendorName',
            span: 24,
            disabled: true
          },
          {
            label: '送货单',
            span: 24,
            prop: 'asnNo'
          },
          {
            label: '供应商批次',
            span: 24,
            prop: 'vendorLotNo',
            rules: [
              {
                required: true,
                message: '请输入供应商批次',
                trigger: 'submit'
              }
            ]
          },
          {
            label: 'D/C',
            span: 24,
            prop: 'dateCode',
            rules: [
              {
                required: true,
                message: '请输入D/C',
                trigger: 'submit'
              }
            ]
          },
          {
            label: '备注',
            span: 24,
            prop: 'description'
          }
        ]
      },
      data: [],
      form: {},
      query: {},
      bindLeftLoading: false,
      loading: false,
      selectionList: [],
      option: {
        height: 'calc(100vh - 289px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 4,
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: false,
        addBtn: false,
        refreshBtn: false,
        columnBtn: false,
        selection: true,
        dialogClickModal: false,
        menu: false,
        labelWidth: 120,
        // cellBtn: true,
        delBtn: false,
        column: [
          {
            label: '行号',
            prop: 'purchaseOrderLot'
          },
          {
            label: '物料编码',
            prop: 'partNo'
          },
          {
            label: '物料型号',
            prop: 'partModel'
          },
          {
            label: '单位',
            prop: 'uom'
          },
          {
            label: '订单数量',
            prop: 'quantity'
          },
          {
            label: '本次收货数量',
            prop: 'receivingQuantity',
            cell: true
          }
        ]
      },
      visibile: false,
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      finishReceive: []
    };
  },
  computed: {
    ...mapGetters(['permission'])
  },
  created() {},
  mounted() {
    focusInput('purchaseOrderNo');
  },
  methods: {
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    openSheetNoModal() {
      this.modalName = 'sheetNoModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择采购单（双击进行选择）',
        url: '/api/mes-warehouse/purchase-order/page?status=1',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '采购单号',
            prop: 'purchaseOrderNo',
            search: true
          },
          {
            label: '供应商代码',
            prop: 'vendorCode',
            search: true
          },
          {
            label: '采购日期',
            prop: 'updateTime'
          }
        ]
      };
    },
    // 获取选择的物料模态框行数据
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'sheetNoModal':
          this.sheetNoInfo;
          // this.sheetNoInfo.sheetNo = this._get(rowData, 'sheetNo', '');
          // this.sheetNoInfo.partnerName = this._get(rowData, 'partnerName', '');
          // this.verifyPackNo(this._get(rowData, 'purchaseOrderNo', ''));
          this.getPurcahasePartDetail(this._get(rowData, 'purchaseOrderNo', ''));
          break;
        default:
          break;
      }
    },
    /**
     * 获取采购单下的物料信息
     */
    getPurcahasePartDetail(purchaseOrderNo) {
      getSheetDetail([purchaseOrderNo]).then(
        (res) => {
          this.data = this._get(res, 'data.data', []);
          this.sheetNoInfo.purchaseOrderNo = this.data[0] ? this.data[0].purchaseOrderNo : '';
          this.sheetNoInfo.vendorName = this.data[0] ? this.data[0].vendorName : '';
          this._forEach(this.data, (item) => {
            item.$cellEdit = true;
            item.quantity = parseFloat(ransferToNumber(this._get(item, 'quantity', 0)));
            item.receivingQuantity = undefined;
          });
        },
        (error) => {
          this.data = [];
        }
      );
    },
    receivingQuantityKeyup(row, index) {
      let params = {
        partMasterId: row.partMasterId,
        partNo: row.partNo,
        receiveQuantity: row.receivingQuantity,
        receiveType: 'PO_SINGLE',
        sheetNo: this.sheetNoInfo.purchaseOrderNo,
        purchaseOrderLot: row.purchaseOrderLot,
        sheetType: 'PO'
      };
      this.checkIntoReceive(params, index);
    },
    checkIntoReceive(params, index) {
      checkReceiving(params).then(
        (res) => {
          let isAlreadyReceivingToday = this._get(res, 'data.data.isAlreadyReceivingToday', false);
          if (isAlreadyReceivingToday) {
            this.$confirm('该订单在24小时内已经进行过收料，请确认?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            });
          }
        },
        (error) => {
          this.data[index].receivingQuantity = '';
        }
      );
    },
    // 重新加载公用表格弹窗组件
    newKey() {
      this.timer = new Date().getTime();
    },
    submit(form, done) {
      let reg = /^\d*(?:\.\d{1,5})?$/;
      for (let i = 0; i < this.data.length; i++) {
        if (Number(this.data[i].receivingQuantity) <= 0) {
          this.$message.warning('本次收货数量不能小于等于0！请重新输入！');
          done();
          return;
        }
        if (Number(this.data[i].receivingQuantity) && !reg.test(Number(this.data[i].receivingQuantity))) {
          this.$message.warning('本次收货数量为数字，并且小数位为5！');
          done();
          return;
        }
      }
      this.finishReceive = [];
      this._forEach(this.data, (item, index) => {
        if (item.receivingQuantity) {
          this.finishReceive.push(item);
        }
      });
      let receivingList = this._map(this.finishReceive, (item) => {
        let params = {
          sheetId: item.id,
          sheetNo: this.sheetNoInfo.purchaseOrderNo,
          purchaseOrderId: item.id,
          purchaseOrderNo: this.sheetNoInfo.purchaseOrderNo,
          purchaseOrderLot: item.purchaseOrderLot,
          partMasterId: item.partMasterId,
          partName: item.partName,
          partModel: item.partModel,
          partNo: item.partNo,
          partBrand: item.partBrand,
          partSpec: item.partSpec,
          vendorId: item.vendorId,
          vendorCode: item.vendorCode,
          vendorName: item.vendorName,
          receiveQuantity: item.receivingQuantity,
          generationType: item.generationType
        };
        return params;
      });
      let paramsMap = {
        asnNo: this.sheetNoInfo.asnNo,
        receiveType: 'PO_SINGLE',
        remark: this.sheetNoInfo.description,
        vendorLotNo: this.sheetNoInfo.vendorLotNo,
        dateCode: this.sheetNoInfo.dateCode,
        receivingList: receivingList
      };
      receivingSubmit(paramsMap).then(
        (res) => {
          this.$message.success(res.data.msg);
          this.sheetNoInfo = {};
          this.$refs.barCodeForm.resetFields();
          this.data = [];
          focusInput('purchaseOrderNo');
          done();
        },
        (error) => {
          done();
        }
      );
    },
    emptytChange() {
      this.$refs.barCodeForm.resetFields();
      this.data = [];
    },
    receivingQuantityChange(row, index) {
      if (row.receivingQuantity) {
        if (row.receivingQuantity == 0) {
          this.$message.warning('本次收货数量不能等于0！');
        } else {
          this.receivingQuantityKeyup(row, index);
        }
      }
    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep .el-card .is-never-shadow {
  padding: 0 !important;
}
::v-deep .partInfoCrud {
  .el-card__body {
    .avue-crud__menu {
      display: none;
    }
  }
}
</style>
